import React from "react";
import { Footer } from "../../packages/excalidraw/index";
import { EncryptedIcon } from "./EncryptedIcon";
import { ExcalidrawPlusAppLink } from "./ExcalidrawPlusAppLink";
import { isExcalidrawPlusSignedUser } from "../app_constants";
import { useExcalidrawActionManager } from "../../packages/excalidraw/components/App";
import { loadFromBlob, normalizeFile } from "../../packages/excalidraw/data/blob";
import { StoreAction } from "../../packages/excalidraw/store";

export const AppFooter = React.memo(() => {
  let u = new URL(location.href)
  const path = u.searchParams.get('fileUrl')
  const actionManager = useExcalidrawActionManager();
  if (path != null) {
    u.pathname = "/_lzc/files/home"+path;
    u.searchParams.delete('fileUrl');
    console.log(u);

    const fetchData = async () => {
      const response = await fetch(u);
      if (!response.ok) {
        throw new Error(`Failed to fetch file: ${response.statusText}`);
      }
      // Read the response as a binary data
      const arrayBuffer = await response.arrayBuffer();
      let input = response.headers.get("Content-Type")
      const parts = input ? input.split("/") : [];
      if (parts[1] == "excalidraw"){
        input = "application/vnd.excalidraw+json"
      }
      console.log(input);
      const file = new File([arrayBuffer], "123hello", { type: input || undefined });
      const actionResult = await loadFromBlob(
        await normalizeFile(file),
        actionManager.getAppState(),
        actionManager.getElementsIncludingDeleted(),
        file.handle,
      );
      actionManager.updater({
        ...actionResult,
        storeAction: StoreAction.CAPTURE,
      });
    };

    fetchData();
  }

  return (
    <Footer>
      <div
        style={{
          display: "flex",
          gap: ".5rem",
          alignItems: "center",
        }}
      >
        {isExcalidrawPlusSignedUser ? (
          <ExcalidrawPlusAppLink />
        ) : (
          <EncryptedIcon />
        )}
      </div>
    </Footer>
  );
});
